#include "IPNGImageMerger.hxx"
#include "IPNGUtils.hxx"

IPNGImageMerger::IPNGImageMerger()
{
    strcpy(_fileSuffix,"png");
}

bool IPNGImageMerger::mergeTileFiles()
{
    bool ret = createTargetImage(false);

    if( !ret ) return ret;
 
    std::vector<std::string> files;

    ListFiles(this->_sourceDir,_fileSuffix, files);

    if( files.size() <  1 )
        return false;

    char filePath[256];
    char *fileName = 0;

    char formatString[256];
    sprintf(formatString, "Tile_R%%d_C%%d.%s", _fileSuffix);

    cv::Mat pngPalette;

    for(int i = 0; i < files.size(); i ++)
    {
        int rowIdx = 0;
        int colIdx = 0;

        memset(filePath,0,256);

        strncpy(filePath,files.at(i).c_str(),files.at(i).size());

        fileName = strstr(filePath, "Tile");

        sscanf(fileName, formatString, &rowIdx, &colIdx);

        printf("%s\n", fileName);

        FILE* file = fopen(filePath, "rb");
        
        fseek(file, 0L, SEEK_END);

        int fileSize = ftell(file);
        
        fseek(file, 0L, SEEK_SET);
        
        char* buffer = new char[fileSize];
        
        fread(buffer, fileSize, 1, file);
        
        fclose(file);
        
        printf("File Size:%d\n", fileSize);

        cv::Mat pngData; 
        
        imdecode_palette_png( buffer, fileSize, pngData, pngPalette );
        
        delete [] buffer;
        
        cv::Mat mask = _targetImage(cv::Rect(colIdx * 1024, rowIdx * 1024, 1024, 1024));

        pngData.copyTo(mask);
    }

    vector<uchar> fileData = imencode_palette_png(_targetImage, pngPalette);


    FILE* file = fopen(_destFileName, "wb");
    fwrite(reinterpret_cast<const char *>(&fileData[0]),fileData.size(),1, file);
    fclose(file);
    
    return true;
}